package cn.tedu.cs.baking.controller;

import cn.tedu.cs.baking.common.ex.BusinessException;
import cn.tedu.cs.baking.dao.PictureMapper;
import cn.tedu.cs.baking.pojo.dto.PictureDTO;
import cn.tedu.cs.baking.pojo.po.Picture;
import cn.tedu.cs.baking.pojo.vo.PictureVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/picture")
@Api(tags = "图片管理")
@Slf4j
public class PictureController {
    @Value("${file.save-path}")
    private String dirPath;

    @Autowired
    private PictureMapper pictureMapper;

    @PostMapping("/addNew")
    @ApiOperation("新增图片")
    public void addNew(@Valid @RequestBody PictureDTO pictureDTO){
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureDTO, picture);
        picture.setCreateTime(new Date());
        pictureMapper.insert(picture);
    }

    @GetMapping("/list")
    @ApiOperation("图片列表")
    public List<PictureVO> getList(
            @RequestParam(required = true,defaultValue = "1") Integer pageCurrent,
            @RequestParam(required = true,defaultValue = "10") Integer pageSize){
        int index = pageSize*(pageCurrent-1);
        List<PictureVO> list = pictureMapper.getList(index,pageSize);
        return list;
    }

    @GetMapping("/listByAlbumId")
    @ApiOperation("根据相册查图片列表")
    public List<PictureVO> getListByAlbumId(Long albumId){
        List<PictureVO> list = pictureMapper.getListByAlbumId(albumId);
        return list;
    }

    @GetMapping("getByPictureId")
    @ApiOperation("图片详情")
    public Picture getByAlbumId(Long id){
        return pictureMapper.selectByPrimaryKey(id);
    }

    @PostMapping("update")
    @ApiOperation("图片更新")
    public void updateById(@Valid @RequestBody PictureDTO pictureDTO){
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureDTO, picture);
        picture.setUpdateTime(new Date());
        pictureMapper.updateByPrimaryKeySelective(picture);
    }

    @GetMapping("/delete")
    @ApiOperation("删除图片")
    public void deleteById(Long pictureId) throws BusinessException {
        //通过id查询图片路径 并删除文件
        String url = pictureMapper.selectUrlById(pictureId);
        //URL = /pic/+dataPath+fileName
        String deleteRul = System.getProperty("user.dir").replaceAll("\\\\", "/") +dirPath.substring(1) +url.substring(5);
        log.info(deleteRul);
        new File(deleteRul).delete();

        int rows = pictureMapper.deleteById(pictureId);
        if (rows != 1){
            throw new BusinessException("删除图片失败!");
        }
    }
}
